package cn.afactory.tygz.ui.base.views.search;

import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.afactory.tygz.R;
import cn.afactory.tygz.ui.base.entity.LoganHotWordEntity;
import cn.afactory.tygz.ui.base.utils.SystemUtils;
import cn.afactory.tygz.ui.base.utils.ViewUtils;

/**
 * Created by wangyouguo on 15/6/30.
 */
public class HotSearchView extends RelativeLayout {
    // 单个item的最小长度
    private static int mMinItemWidth;
    private ViewGroup mRootContainer;
    private int mItemMargin;
    private int mItemPadding;
    private TextPaint mItemTextPaint;
    private OnItemViewClickListener mListener;
    private List<LoganHotWordEntity> mKeywordList = new ArrayList<LoganHotWordEntity>();
    private int mRowSize;

    public HotSearchView(Context context) {
        super(context);
        initView();
    }

    public HotSearchView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public HotSearchView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initView();
    }


    private void initView() {
        View view = (ViewGroup) View.inflate(getContext(), R.layout.search_hot_keyword_layout, null);
        mRootContainer = ViewUtils.findView(view, R.id.container_layout);
        LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT);
        addView(view, lp);

        mItemMargin = getResources().getDimensionPixelOffset(R.dimen.margin_10dp);
        mItemPadding = getResources().getDimensionPixelOffset(R.dimen.margin_10dp);

        mMinItemWidth = mItemMargin * 6;

        View item = View.inflate(getContext(), R.layout.search_hot_keyword_item, null);
        TextView itemTV = (TextView) item.findViewById(R.id.hot_keyword_item);
        mItemTextPaint = itemTV.getPaint();
    }

    public void setData(List<LoganHotWordEntity> datas) {
        if (datas != null) {
            mKeywordList.addAll(datas);
            mRootContainer.removeAllViews();
        }
        updateViews();
    }

    private void updateViews() {
        LinearLayout itemViewGroup = null;
        int leftScreenWidth = getScreenWidth();
        Map<Integer, List<View>> viewMap = new HashMap<Integer, List<View>>();
        int row = 0;
        for (int i = 0; i < mKeywordList.size(); i++) {
            LoganHotWordEntity keyword = mKeywordList.get(i);
            String itemText = keyword.content;
            if (TextUtils.isEmpty(itemText)) {
                continue;
            }
            // 字符的实际大小
            int tvWidth = (int) mItemTextPaint.measureText(itemText);
            tvWidth += mItemPadding * 2;

            // 单个item最小长度
            if (tvWidth < mMinItemWidth) {
                tvWidth = mMinItemWidth;
            }

            //加上间隔之后的大小
            int itemWidth = tvWidth + mItemMargin * 2;

            List<View> viewList = viewMap.get(row);
            if (itemWidth > leftScreenWidth) {
                if (viewList == null) {
                    viewList = new ArrayList<>();
                }
                if (viewList.isEmpty()) {
                    //如果为第一个，则自己占一行后，另起一行
                    viewList.add(createItemTextView(keyword, i, row));
                    row++;
                    leftScreenWidth = getScreenWidth();
                } else {
                    // 如果为该行的最后一个则另起一行，然后添加到列表中
                    row++;
                    leftScreenWidth = getScreenWidth();
                    viewList = new ArrayList<>();
                    viewList.add(createItemTextView(keyword, i, row));
                    viewMap.put(row, viewList);
                    leftScreenWidth -= itemWidth;
                }


            } else {
                // 把子项添加到列表中
                if (viewList == null) {
                    viewList = new ArrayList<>();
                    viewMap.put(row, viewList);
                    leftScreenWidth = getScreenWidth();
                }
                viewList.add(createItemTextView(keyword, i, row));
                leftScreenWidth -= itemWidth;
                //  不是最后一个，所以要加上它的尾部空间，
                // 否则就会把第二个组件的头部间隔也算上了
                leftScreenWidth += mItemMargin;
            }
        }

        setRowSize(viewMap.keySet().size());

        addItem2Container(viewMap);
    }

    /**
     * 获取屏幕的宽度
     *
     * @return
     */
    private int getScreenWidth() {
        return SystemUtils.getSreenWidth(getContext());
    }

    /**
     * 创建每一行的父ViweGroup
     *
     * @param row
     * @return
     */
    private LinearLayout createItemViewGroup(int row) {
        LinearLayout itemViewGroup = new LinearLayout(getContext());
        itemViewGroup.setOrientation(LinearLayout.HORIZONTAL);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.
                MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        //设置行间距
        if (row != getRowSize() - 1) {
            lp.setMargins(0, mItemMargin, 0, 0);
        } else {
            lp.setMargins(0, mItemMargin, 0, mItemMargin);
        }
        itemViewGroup.setLayoutParams(lp);
        return itemViewGroup;
    }

    /**
     * 创建单个子项
     *
     * @param itemContent
     * @param position
     * @param row
     * @return
     */
    private View createItemTextView(LoganHotWordEntity itemContent, int position, int row) {
        View item = View.inflate(getContext(), R.layout.search_hot_keyword_item, null);
        TextView itemTV = (TextView) item.findViewById(R.id.hot_keyword_item);
        itemTV.setText(itemContent.content);
        item.setTag(itemContent);
        return item;
    }

    private void setRowSize(int rowSize) {
        mRowSize = rowSize;
    }

    private int getRowSize() {
        return mRowSize;
    }

    /**
     * 把view添加到布局中
     *
     * @param viewMap
     */
    private void addItem2Container(Map<Integer, List<View>> viewMap) {
        int rows = getRowSize();
        for (int i = 0; i < rows; i++) {
            List<View> viewList = viewMap.get(i);
            LinearLayout itemContainer = createItemViewGroup(i);
            for (int j = 0; j < viewList.size(); j++) {
                View view = viewList.get(j);

                // 设置点击事件
                view.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (mListener != null) {
                            if (v.getTag() instanceof LoganHotWordEntity) {
                                mListener.onItemClick((LoganHotWordEntity) v.getTag());
                            }
                        }
                    }
                });
                itemContainer.addView(view);
                //设置子项间的间距
                LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) view.getLayoutParams();
                if (j != viewList.size() - 1) {
                    lp.setMargins(mItemMargin, 0, 0, 0);
                } else {
                    lp.setMargins(mItemMargin, 0, mItemMargin, 0);
                }
                view.setLayoutParams(lp);

            }
            mRootContainer.addView(itemContainer);

        }
    }

    public void setOnItemViewClickListener(OnItemViewClickListener l) {
        mListener = l;
    }

    public interface OnItemViewClickListener {
        void onItemClick(LoganHotWordEntity item);
    }


}
